package server.jobs;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import server.db.DatabaseFunctor;
import utils.Strings;

import com.google.common.collect.Lists;
import com.google.inject.internal.Maps;
import static server.db.StmtHelper.db;

import feeds.FeedHelper;
import fj.F;
import it.sauronsoftware.cron4j.Scheduler;

public class ListingsJob {

	public static void initializeScheduler() {
			// Creates a Scheduler instance.
			Scheduler getListingsFromZillow = new Scheduler();
			// Schedule a task to be run every night at mid-night
			//"00 00 * * 1-7"
			
			String id = getListingsFromZillow.schedule("50 * * * *", new Runnable() {
				public void run() {
					getFullPull();
				}
			});
			// Starts the scheduler.
			getListingsFromZillow.start();
			getListingsFromZillow.launch(getListingsFromZillow.getTask(id));
	}
	
	private static Map<String,Map<String,String>> listingsMap = Maps.newLinkedHashMap();

	
	public static void getFullPull()
	{
		String result = FeedHelper.getServiceResult(url());
		
		JSONObject obj = new JSONObject();
		SAXParserFactory parser = SAXParserFactory.newInstance();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource ins = new InputSource();
			ins.setCharacterStream(new StringReader(result));
			Document doc = db.parse(ins);
			doc.getDocumentElement().normalize();
			
			NodeList nodeLst = doc.getElementsByTagName("result");
			for(int i=0; i<nodeLst.getLength();i++)
			{
				Map<String,String> listingMap = Maps.newLinkedHashMap();
				
				Node fstNode = nodeLst.item(i);
				 if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
					 fstNode.normalize();
					 Element fstElmnt = (Element) fstNode;
					 NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("property");
					 NodeList children = fstNmElmntLst.item(0).getChildNodes();
					 for(int j = 0; j < children.getLength(); j++)
					 {
						 Node propNode = children.item(j);
						 if (propNode.getNodeType() == Node.ELEMENT_NODE) {
							 Element propElem = (Element)propNode;
							 if(propElem.hasChildNodes())
							 {
								for(int k=0; k<propElem.getChildNodes().getLength();k++)
								{
									if (propElem.getChildNodes().item(k).getNodeType() == Node.ELEMENT_NODE) {
										 Element addrElem = (Element)propElem.getChildNodes().item(k);
										 System.out.println(addrElem.getTagName()+" "+addrElem.getTextContent());
										 listingMap.put(addrElem.getTagName(), addrElem.getTextContent());
									}
								}
							 }
							 System.out.println(propElem.getTagName()+" "+propElem.getTextContent());
							 listingMap.put(propElem.getTagName(), propElem.getTextContent());
						 }
						 	
						 
					 }
					 listingsMap.put(listingMap.get("zpid"), listingMap);
				 }
				
			}
			List<DatabaseFunctor<Integer>> inserts = Lists.newLinkedList();
			
			for(String key : listingsMap.keySet())
			{
				//,street,typ,lotsize," +"finishedSQFT,full_baths,half_baths," +"bedrooms,zip,city,state,lat,lng
				Map oneListing = listingsMap.get(key);
				inserts.add(db("insert into alllist (zillowID,zillowlink,street,useCode,lotsize,finishedSQFT,bedrooms,bathrooms,zip,city,state,lat,lng)" +
					" values(")
					.addVariable(oneListing.get("zpid"))
					.addSql(",").addVariable(oneListing.get("links"))
					.addSql(",").addVariable(oneListing.get("street"))
					.addSql(",").addVariable(oneListing.get("useCode"))
					.addSql(",").addVariable(oneListing.get("lotSizeSqFt"))
					.addSql(",").addVariable(oneListing.get("finishedSqFt"))
					.addSql(",").addVariable(oneListing.get("bedrooms"))
					.addSql(",").addVariable(oneListing.get("bathrooms"))
					.addSql(",").addVariable(oneListing.get("zipcode"))
					.addSql(",").addVariable(oneListing.get("city"))
					.addSql(",").addVariable(oneListing.get("state"))
					.addSql(",").addVariable(oneListing.get("latitude"))
					.addSql(",").addVariable(oneListing.get("longitude"))
					.addSql(") ON DUPLICATE KEY UPDATE ")
					.addSql(" zillowlink=").addVariable(oneListing.get("links"))
					.executeUpdate());
			}
			DatabaseFunctor.sequence(inserts).unsafeUpdate();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String url() {
		return "http://www.zillow.com/webservice/GetRegionPostings.htm?zws-id="+ID+
			"&citystatezip=Austin+Tx";
	}
	
	private static String ID = "X1-ZWz1bwyrxi651n_7aoby";


}
